package com.bw.module_main.ui.splash

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.lib_common.getAttrValue
import com.bw.lib_common.utils.LoggerUtils
import com.bw.lib_storage.AppMMKV
import com.bw.module_main.R
import com.bw.module_main.databinding.ActivitySplashBinding
import com.bw.module_main.dialog.MessageNoticeDialog
import dagger.hilt.android.AndroidEntryPoint
import retrofit2.http.Tag

/**
 * 闪屏页
 */

@AndroidEntryPoint
class SplashActivity : BaseActivity<SplashViewModel,ActivitySplashBinding>(){
    private val mViewModel:SplashViewModel by viewModels()
    companion object{
        const val TAG = "SplashActivity"
        private const val SPLASH_MAX_DELAY: Long = 3_500 //延迟跳转
    }
    override val mLayoutResId: Int
        get() = R.layout.activity_splash
    private val handler by lazy{
        object :Handler(Looper.getMainLooper()){
            override fun handleMessage(msg: Message) {
                if (mViewModel.mAdInfo?.imageUrl.isNullOrEmpty()){
                    if (AppMMKV.appGuide){
                        //走引导页
                        toGuide()
                    }else{
                        //主页面
                        toMain()
                    }
                }else{
                    //广告页
                    toAd()
                }
            }
        }
    }
    override fun initView() {
        super.initView()
    }

    override fun initData() {
        super.initData()
        //1：获得广告数据
        mViewModel.adList()
        //2：处理通知栏点击事件打开app
        //3：处理隐士跳转打开app：分享链接，打开链接
        //4：弹出隐私协议对话框
        val userAgreement = AppMMKV.userAgreement
        LoggerUtils.d(TAG,userAgreement.toString())
        if (!userAgreement){

            val colorMain = getAttrValue(this, com.bw.lib_common.R.attr.colorTheme)
            val userAgreement = "《用户协议》"
            val privacyPolicy = "《隐私条款》"
            val content =
                "宗申骑士俱乐部非常尊重用户个人的信息保护，我们依据最新的监管要求特向您说明如下：\n1.在使用 APP过程中，我们有可能会收集、使用设备标识信息用于推送车辆提醒消息。\n2.我们会一直采取严格的安全技术保护您的个人信息安全。\n3.未经您的同意，我们不会以协议约定之外的形式和渠道获取、共享或使用您的个人信息。\n您可通过阅读完整的${userAgreement}和${privacyPolicy}来了解详细信息。请您充分阅读并理解以上协议，点击同意按钮，即表示您已同意上述协议及以上约定。"
            val spannableStringBuilder = SpannableStringBuilder(content)
            val userAgreementStart = content.indexOf(userAgreement)
            val userAgreementEnd = userAgreementStart + userAgreement.length
            val privacyPolicyStart = content.indexOf(privacyPolicy)
            val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpUserAgreement()
                    showToast("点击了用户")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, colorMain) //红色
                    ds.isUnderlineText = false
                }

            }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpPrivacyAgreement()
                    showToast("点击了隐私")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, colorMain)
                    ds.isUnderlineText = false
                }

            }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)


            MessageNoticeDialog(
                title = "温馨提示",
                message = spannableStringBuilder,  //富文本
                onConfirmClick = {
                    AppMMKV.userAgreement =  true
                    handler.sendEmptyMessageDelayed(0,SPLASH_MAX_DELAY)

                },
                onCancelClick = {
                    finish()
                },
                onlyConfirmButton = false,
                confirmText = "同意",
                cancelText = "不同意",
                cancelable = false,
                alignment = Gravity.LEFT,

            ).show(supportFragmentManager)

        }else{
            handler.sendEmptyMessageDelayed(0,SPLASH_MAX_DELAY)
        }


    }

    override fun initListener() {
        super.initListener()
    }
    fun toAd(){
        ARouter.getInstance().build(Router.Ui.AdActivity)
            .withSerializable("mAdModel",mViewModel.mAdInfo)
            .navigation()
        finish()
    }

    fun toGuide(){
        ARouter.getInstance().build(Router.Ui.GuideActivity).navigation()
        finish()
    }

    fun toMain(){
        ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null) //页面销毁。移除handler中未处理的消息，防止内存泄露
        //页面销毁，activity应该被回收，但是handler持有activity的引用，handler还有未处理完的消息，这样会导致activity无法被回收，最终导致内存泄露
    }


}